﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using com.codebump;

public partial class CityLookup : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSearchZip_Click(object sender, EventArgs e)
    {

        ddlCity.Items.Clear();
        ddlCity.Enabled = true;

        if (System.Text.RegularExpressions.Regex.IsMatch(tbZip.Text.ToUpper(), @"(^\d{5}$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)"))
        {
            try
            {

                GeoPlaces g = new GeoPlaces();

                AuthenticationHeader authHeader = new AuthenticationHeader();
                authHeader.SessionID = "6JV2ZA4lgG1YRR+HG+JU27QWk9zI3rpRWY2iG2mzNPcdieEQXfQv0OUY0EZ+pOTxhwI1NCuF7b2oY+U/bozy0mhjFHmpaXvb";
                g.AuthenticationHeaderValue = authHeader;

                //GeoPlaceDistance[] places = g.GetPlacesWithin("Los Angeles", "CA", 10, GeoPlaceType.ZipCode);
                GeoPlaceDistance[] places = g.GetPlacesInside(tbZip.Text, "");

                for (int i = 0; i < places.Length; i++)
                {
                    GeoPlaceDistance place = places[i];
                    ListItem li = new ListItem(place.ToPlace, place.ToState + "," + place.ToPlace);
                    ddlCity.Items.Add(li);
                }

                ddlState.Items.Clear();
                ddlState.Items.Add(ddlCity.SelectedItem.Value.Split(",".ToCharArray())[0]);

                //ddlCity.SelectedIndex = 0;

                if (System.Text.RegularExpressions.Regex.IsMatch(tbZip.Text.ToUpper(), @"(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)"))
                {
                    ddlCountry.SelectedValue = "CANADA";
                }
                else
                {
                    ddlCountry.SelectedValue = "USA";
                }

                if (ddlCity.Items.Count == 1)
                {
                    ddlCity.Enabled = false;

                    //tbState.Text += ddlCity.SelectedItem.Value.ToString();
                }
                else if (ddlCity.Items.Count <= 0)
                {
                    ddlCity.Items.Add("No Cities Found");
                    ddlCity.Enabled = false;
                }
                else
                {
                }
            }
            catch
            {
                ddlCity.Items.Add("No Cities Found");
                ddlCity.Enabled = false;
            }
        }
        else
        {
            ddlCity.Items.Add("Invalid Zip");
            ddlCity.Enabled = false;
        }
    }
}